package me.yuzho.study.concurrency;

import java.util.concurrent.TimeUnit;

class DualSynch {
    private Object syncObject = new Object();
    
    public synchronized void f() throws InterruptedException{
        for(int i=0; i<5; i++) {
            System.out.println("f()");
            TimeUnit.SECONDS.sleep(1);
            Thread.yield();
        }
    }
    
    public void g() throws InterruptedException {
        synchronized(syncObject) { //用syncObject代替THIS，f()被一个线程调用时，不会阻塞其它线程对g()的调用
            for(int i=0; i<5; i++) {
                System.out.println("g()");
                TimeUnit.SECONDS.sleep(1);
                Thread.yield();
            }
        }
    }
}

public class SyncObject {

    public static void main(String[] args) throws InterruptedException {
        
        final DualSynch ds = new DualSynch();
        
        new Thread() {
            public void run() {
                try {
                    ds.f();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }.start();
        
        ds.g();
    }

}
